//
// Created by miaomiaole on 2024/1/26.
//
#include <opencv2\opencv.hpp>
#include <iostream>
#include <opencv2\imgproc\types_c.h> //for CV_RGB2GRAY
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace std;

int main() {
    Mat gray;
    auto home = imread("./IMG_20161003_182919.jpg");

    cvtColor(home, gray, CV_RGB2GRAY);


    int bins = 256;
    int hist_size[] = {bins};
    float range[] = {0, 256};
    const float *ranges[] = {range};
    MatND hist;
    int channels[] = {0};
    calcHist(&gray, 1, channels, Mat(),
             hist, 1, hist_size, ranges,
             true,
             false);


    double max_val;
    minMaxLoc(hist, 0, &max_val, 0, 0);

    int scale = 2;
    int hist_height = 256;
    //创建一个全0的特殊矩阵
    Mat hist_img = Mat::zeros(hist_height, bins * scale, CV_8UC3);


    for (int i = 0; i < bins; i++) {
        float bin_val = hist.at<float>(i);
        int intensity = cvRound(bin_val * hist_height / max_val);  //要绘制的高度
        rectangle(hist_img, Point(i * scale, hist_height - 1),  //画矩形
                  Point((i + 1) * scale - 1, hist_height - intensity),
                  CV_RGB(255, 255, 255));
    }


    namedWindow("source",WINDOW_NORMAL);
    namedWindow("hist_img",WINDOW_NORMAL);
    //显示原图和直方图
    imshow("source", home);
    imshow("hist_img", hist_img);

    waitKey(0);

}